package com.gogowan.agroenterprise.storage;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.TitleActivity;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask.AsyncLoadListener;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask.InterActionModel;
import com.gogowan.agroenterprise.model.AddressInfo;
import com.gogowan.agroenterprise.model.AreaInfo;
import com.gogowan.agroenterprise.model.DealerListResult;
import com.gogowan.agroenterprise.model.DealerModel;
import com.gogowan.agroenterprise.model.DealerRequest;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.utils.PalUtils;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.xlistview.LoadingLayout;

/**
 * @Description:经销商详情
 * @author mdp
 * @date 2017年1月5日 上午11:05:53
 */
public class DealerDetailsActivity extends TitleActivity implements
		AsyncLoadListener {

	private DealerModel dealerModel = new DealerModel();
	private int flag;
	private static final int ADDR_RQT1 = 1;
	private static final int ADDR_RQT2 = 2;
	private static final int REFRESH_RQT = 3;
	private static final int COMMIT_RQT = 4;
	private static final int ADDR_RQC = 1;
	// s-handler
	private static final int RELOAD_HDL = 1;
	private static final int RELOAD_ADDR_HDL = 2;
	private static final int REFRESHED_HDL = 3;
	private WeakRefAsyncTask weakRefAsyncTask = new WeakRefAsyncTask(this);
	private LoginResultInfo loginResult;
	private AreaInfo areaInfo = new AreaInfo();
	private LoadingLayout loadingLayout;
	private TextView dealer_details_qy_et;
	private EditText dealer_details_jxsmc_et, dealer_details_lxr_et,
			dealer_details_dz_et, dealer_details_dlm_et,
			dealer_details_dlmm_et, dealer_details_lxdh_et;
	private ImageView dealer_details_lxdh_im;
	private Button dealer_details_commit_btn;

	@Override
	protected int setContentViewID() {
		return R.layout.activity_dealer_details;
	}

	@Override
	protected boolean initData(Intent intent, Bundle savedInstanceState) {
		loginResult = PalUtils.getLoginResultInfo(getApplicationContext());
		dealerModel = (DealerModel) intent
				.getSerializableExtra(PalUtils.PACK_MODEL_ITT);
		if (dealerModel == null) {
			dealerModel = new DealerModel();
		}
		flag = intent.getIntExtra(PalUtils.PACK_TYPE_ITT, 0);
		return loginResult != null && flag != 0;
	}

	@Override
	protected void initView() {
		initTitle("经销商详情", (dealerModel.getSupplier()!=null?true:false), R.drawable.delete, new OnRightListener() {
			@Override
			public void onClick() {
				DeleteHttp();
			}
		});
		dealer_details_jxsmc_et = (EditText) findViewById(R.id.dealer_details_jxsmc_et);
		dealer_details_lxr_et = (EditText) findViewById(R.id.dealer_details_lxr_et);
		dealer_details_dz_et = (EditText) findViewById(R.id.dealer_details_dz_et);
		dealer_details_qy_et = (TextView) findViewById(R.id.dealer_details_qy_et);
		dealer_details_dlm_et = (EditText) findViewById(R.id.dealer_details_dlm_et);
		dealer_details_dlmm_et = (EditText) findViewById(R.id.dealer_details_dlmm_et);
		dealer_details_lxdh_et = (EditText) findViewById(R.id.dealer_details_lxdh_et);
		dealer_details_lxdh_im = (ImageView) findViewById(R.id.dealer_details_lxdh_im);
		dealer_details_commit_btn = (Button) findViewById(R.id.dealer_details_commit_btn);
		dealer_details_lxdh_im.setOnClickListener(this);
		dealer_details_qy_et.setOnClickListener(this);
		loadingLayout = (LoadingLayout) findViewById(R.id.dealer_details_loadingLayout);
		loadingLayout.setReplacedView(findViewById(R.id.dealer_details_sv));
		if (flag == 2) {
			loadingLayout.showLoading();
			requestAddr();
			setEnabled(false);
		} else {
			setEnabled(true);
		}
	}

	private void DeleteHttp() {
		String json = Utils.toJSON(dealerModel);
		Message message = new Message(PalUtils.MsgType.DeleteDealer,
				PalUtils.ENCRYPT, json);
		InterActionModel interActionModel = new InterActionModel();
		interActionModel.setIndex(PalUtils.MsgType.DeleteDealer);
		interActionModel.setUrl(getString(R.string.first_url)
				+ getString(R.string.first_url_page));
		interActionModel.setMessage(message);
		weakRefAsyncTask.execute(interActionModel);

	}

	@Override
	protected void onClicked(View v) {
		switch (v.getId()) {
		// 电话
		case R.id.dealer_details_lxdh_im:
			String telStr = dealer_details_lxdh_et.getText().toString().trim();
			if (!PalUtils.isEmpty(telStr)) {
				startActivity(PalUtils.getCallIntent(telStr, false));
			}
			break;
		// 地址
		case R.id.dealer_details_qy_et:
			if (areaInfo == null || PalUtils.isEmpty(areaInfo.getAddressList())) {
				requestAddr();
				return;
			}
			Intent intent = new Intent(this, LocationWheelActivity.class);
			intent.putExtra(PalUtils.PACK_MODEL_ITT, areaInfo);
			startActivityForResult(intent, ADDR_RQC);
			break;
		}
	}

	@Override
	public void handleMessage(TitleActivity activity, android.os.Message msg) {
		switch (msg.what) {
		case RELOAD_ADDR_HDL:
			loadingLayout.showReload(new LoadingLayout.OnReloadClickListener() {
				@Override
				public void onClick() {
					requestAddr();
				}
			});
			break;
		case RELOAD_HDL:
			loadingLayout.showReload(new LoadingLayout.OnReloadClickListener() {
				@Override
				public void onClick() {
					refresh();
				}
			});
			break;
		case REFRESHED_HDL:
			dealer_details_qy_et.setText(getAddrName(dealerModel.getSheng(),
					dealerModel.getShi(), dealerModel.getQu()));
			dealer_details_jxsmc_et.setText(dealerModel.getSupplier());
			dealer_details_lxr_et.setText(dealerModel.getLinkMan());
			dealer_details_dz_et.setText(dealerModel.getAddress());
			dealer_details_dlm_et.setText(dealerModel.getLoginName());
			dealer_details_dlmm_et.setText(dealerModel.getPassWord());
			dealer_details_lxdh_et.setText(dealerModel.getPhoneNum());
			loadingLayout.hide();
			break;
		default:
			break;
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			// 地域选择
			case ADDR_RQC:
				ArrayList<String> addr = intent
						.getStringArrayListExtra("location");
				dealerModel.setSheng(Integer.parseInt(addr.get(1)));
				dealerModel.setShi(Integer.parseInt(addr.get(3)));
				dealerModel.setQu(Integer.parseInt(addr.get(5)));
				dealer_details_qy_et.setText(getAddrName(
						dealerModel.getSheng(), dealerModel.getShi(),
						dealerModel.getQu()));
				break;
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		weakRefAsyncTask.cancel();
	}

	@Override
	public void onResult(AsyncLoadListener asyncLoadListener, String response,
			int actionId) {
		hideProgressDialog();
		if (isAlreadyDestroyed()) {
			return;
		}
		if (PalUtils.isEmpty(response)) {
			PalUtils.showShortToast(getApplicationContext(),
					getString(R.string.server_error));
			if (actionId == ADDR_RQT2) {
				getWeakRefHandler().sendEmptyMessage(RELOAD_ADDR_HDL);
			} else if (actionId == REFRESH_RQT) {
				getWeakRefHandler().sendEmptyMessage(RELOAD_HDL);
			}
		} else {
			switch (actionId) {
			// 添加-地址
			case ADDR_RQT1:
				AreaInfo areaInfo1 = (AreaInfo) PalUtils.getPostResult(
						response, AreaInfo.class);
				if (areaInfo1 == null) {
					PalUtils.showShortToast(getApplicationContext(),
							getString(R.string.analyse_error));
				} else if (areaInfo1.getResultCode() == 1) {
					if (PalUtils.isEmpty(areaInfo1.getAddressList())) {
						PalUtils.showShortToast(getApplicationContext(),
								getString(R.string.analyse_error));
						return;
					}
					this.areaInfo = areaInfo1;
					Intent intent = new Intent(this,
							LocationWheelActivity.class);
					intent.putExtra(PalUtils.PACK_MODEL_ITT, areaInfo);
					startActivityForResult(intent, ADDR_RQC);
				} else {
					PalUtils.showShortToast(getApplicationContext(),
							areaInfo1.getResultMsg());
				}
				break;
			// 修改-地址
			case ADDR_RQT2:
				AreaInfo areaInfo = (AreaInfo) PalUtils.getPostResult(response,
						AreaInfo.class);
				if (areaInfo == null) {
					getWeakRefHandler().sendEmptyMessage(RELOAD_ADDR_HDL);
					PalUtils.showShortToast(getApplicationContext(),
							getString(R.string.analyse_error));
				} else if (areaInfo.getResultCode() == 1) {
					if (PalUtils.isEmpty(areaInfo.getAddressList())) {
						getWeakRefHandler().sendEmptyMessage(RELOAD_ADDR_HDL);
						return;
					}
					this.areaInfo = areaInfo;
					refresh();
				} else {
					getWeakRefHandler().sendEmptyMessage(RELOAD_ADDR_HDL);
					PalUtils.showShortToast(getApplicationContext(),
							areaInfo.getResultMsg());
				}
				break;
			// 获取经销商信息
			case REFRESH_RQT:
				DealerModel dealerModel = (DealerModel) PalUtils.getPostResult(
						response, DealerModel.class);
				if (dealerModel == null) {
					getWeakRefHandler().sendEmptyMessage(RELOAD_HDL);
					PalUtils.showShortToast(getApplicationContext(),
							getString(R.string.analyse_error));
				} else if (dealerModel.getResult() > 0) {
					this.dealerModel = dealerModel;
					getWeakRefHandler().sendEmptyMessage(REFRESHED_HDL);
				} else {
					getWeakRefHandler().sendEmptyMessage(RELOAD_HDL);
					PalUtils.showShortToast(getApplicationContext(),
							dealerModel.getResultinfo());
				}
				break;
			// 提交
			case COMMIT_RQT:
				DealerListResult storeListResult = (DealerListResult) PalUtils
						.getPostResult(response, DealerListResult.class);
				if (storeListResult == null) {
					PalUtils.showShortToast(getApplicationContext(),
							getString(R.string.analyse_error));
				} else if (storeListResult.getResult() > 0) {
					PalUtils.showShortToast(getApplicationContext(),
							storeListResult.getResultinfo());
					setResult(RESULT_OK);
					if (flag == 2) {
						finish();
					} else {
						this.dealerModel = new DealerModel();
						getWeakRefHandler().sendEmptyMessage(REFRESHED_HDL);
					}
				} else {
					PalUtils.showShortToast(getApplicationContext(),
							storeListResult.getResultinfo());
				}
				break;
				case PalUtils.MsgType.DeleteDealer:
					setResult(PalUtils.MsgType.DeleteDealer);
					finish();
					break;
			}
		}
	}

	/**
	 * 置灰
	 * */
	private void setEnabled(final boolean isEnabled) {
		dealer_details_qy_et.setEnabled(isEnabled);
		dealer_details_jxsmc_et.setEnabled(isEnabled);
		dealer_details_lxr_et.setEnabled(isEnabled);
		dealer_details_qy_et.setEnabled(isEnabled);
		dealer_details_dz_et.setEnabled(isEnabled);
		dealer_details_dlm_et.setEnabled(isEnabled);
		dealer_details_dlmm_et.setEnabled(isEnabled);
		dealer_details_lxdh_et.setEnabled(isEnabled);
		dealer_details_lxdh_im.setEnabled(!isEnabled);
		dealer_details_commit_btn.setText(isEnabled ? "完  成" : "编辑经销商");
		dealer_details_commit_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isEnabled) {
					commit();
				} else {
					setEnabled(true);
				}
			}
		});
	}

	/**
	 * 显示地域名(去重)
	 * 
	 * @param shengId
	 *            省
	 * @param shiId
	 *            市
	 * @param quId
	 *            区
	 * */
	private String getAddrName(long shengId, long shiId, long quId) {
		String sheng = "";
		String shi = "";
		String qu = "";
		String name = "";
		if (shengId == 0 || shiId == 0 || quId == 0) {
			return "";
		}
		for (AddressInfo addressInfo : areaInfo.getAddressList()) {
			if (addressInfo.getAddress_ID() == shengId) {
				sheng = addressInfo.getAddressName();
			}
			if (addressInfo.getAddress_ID() == shiId) {
				shi = addressInfo.getAddressName();
			}
			if (addressInfo.getAddress_ID() == quId) {
				qu = addressInfo.getAddressName();
			}
		}
		if (!sheng.equals(shi)) {
			if (!shi.equals(qu)) {
				name = sheng + shi + qu;
			} else {
				name = sheng + shi;
			}
		} else {
			if (!shi.equals(qu)) {
				name = shi + qu;
			} else {
				name = shi;
			}
		}
		return name;
	}

	/**
	 * 获取地址信息
	 * */
	private void requestAddr() {
		if (flag == 1) {
			showProgressDialog(getString(R.string.alert_message));
		}
		DealerRequest dealerRequest = new DealerRequest();
		//dealerRequest.setEnterpriseID(loginResult.getEnterpriseinfo()
				//.getEnterpriseid());
		//dealerRequest.setUserID(loginResult.getUserinfo().getPersonid());
		//dealerRequest
				//.setUserType(loginResult.getEnterpriseinfo().getUserType());
		dealerRequest.setDealerID(dealerModel.getId());
		// dealerRequest.setDealerName(dealerModel.getDealerName());
		String json = Utils.toJSON(dealerRequest);
		Message message = new Message(PalUtils.MsgType.GetAreaInfo,
				PalUtils.ENCRYPT, json);
		InterActionModel interActionModel = new InterActionModel();
		interActionModel.setIndex(flag == 1 ? ADDR_RQT1 : ADDR_RQT2);
		interActionModel.setUrl(getString(R.string.first_url)
				+ getString(R.string.first_url_page));
		interActionModel.setMessage(message);
		weakRefAsyncTask.execute(interActionModel);
	}

	/**
	 * 获取详情信息
	 * */
	private void refresh() {
		DealerRequest dealerRequest = new DealerRequest();
//		dealerRequest.setEnterpriseID(loginResult.getEnterpriseinfo()
//				.getEnterpriseid());
		//dealerRequest.setUserID(loginResult.getUserinfo().getPersonid());
		//dealerRequest
				//.setUserType(loginResult.getEnterpriseinfo().getUserType());
		dealerRequest.setDealerID(dealerModel.getId());
		String json = Utils.toJSON(dealerRequest);
		Message message = new Message(PalUtils.MsgType.GetDealerInfo,
				PalUtils.ENCRYPT, json);
		InterActionModel interActionModel = new InterActionModel();
		interActionModel.setIndex(REFRESH_RQT);
		interActionModel.setUrl(getString(R.string.first_url)
				+ getString(R.string.first_url_page));
		interActionModel.setMessage(message);
		weakRefAsyncTask.execute(interActionModel);
	}

	/**
	 * 提交
	 * */
	private void commit() {
		if (PalUtils
				.checkEmpty(getApplicationContext(), dealer_details_jxsmc_et
						.getText().toString().trim(), "请输入经销商名称")) {
			return;
		}
		if (PalUtils.checkEmpty(getApplicationContext(), dealer_details_lxr_et
				.getText().toString().trim(), "请输入联系人")) {
			return;
		}
		if (PalUtils.checkEmpty(getApplicationContext(), dealer_details_qy_et
				.getText().toString().trim(), "请选择区域")) {
			return;
		}
		if (PalUtils.checkEmpty(getApplicationContext(), dealer_details_dz_et
				.getText().toString().trim(), "请输入地址")) {
			return;
		}
		if (PalUtils.checkEmpty(getApplicationContext(), dealer_details_dlm_et
				.getText().toString().trim(), "请输入登录名")) {
			return;
		}
		if (PalUtils.checkEmpty(getApplicationContext(), dealer_details_dlmm_et
				.getText().toString().trim(), "请输入登录密码")) {
			return;
		}
		if (dealer_details_dlmm_et.getText().toString().length() < 6) {
			PalUtils.showShortToast(getApplicationContext(), "请输入6位以上登录密码");
			return;
		}
		if (PalUtils.checkEmpty(getApplicationContext(), dealer_details_lxdh_et
				.getText().toString().trim(), "请输入电话号码")) {
			return;
		}
		if (!PalUtils.matchesRegex(PalUtils.REGEX_MOBILE,
				dealer_details_lxdh_et.getText().toString().trim())
				&& !PalUtils.matchesRegex(PalUtils.REGEX_TEL,
						dealer_details_lxdh_et.getText().toString().trim())) {
			PalUtils.showShortToast(getApplicationContext(), "电话号码格式错误");
			return;
		}
		showProgressDialog(getString(R.string.committing));
//		dealerModel.setEnterprisseID(loginResult.getEnterpriseinfo()
//				.getEnterpriseid());
		//dealerModel.setUserType(loginResult.getEnterpriseinfo().getUserType());
		//dealerModel.setAddUser(loginResult.getUserinfo().getPersonid());
		dealerModel.setSupplier(dealer_details_jxsmc_et.getText().toString()
				.trim());
		dealerModel.setLinkMan(dealer_details_lxr_et.getText().toString()
				.trim());
		dealerModel
				.setAddress(dealer_details_dz_et.getText().toString().trim());
		dealerModel.setLoginName(dealer_details_dlm_et.getText().toString()
				.trim());
		dealerModel.setPassWord(dealer_details_dlmm_et.getText().toString()
				.trim());
		dealerModel
				.setPhoneNum(dealer_details_lxdh_et.getText().toString().trim());
		String json = Utils.toJSON(dealerModel);
		Message message = new Message(flag == 1 ? PalUtils.MsgType.AddDealer
				: PalUtils.MsgType.EditDealer, PalUtils.ENCRYPT, json);
		InterActionModel interActionModel = new InterActionModel();
		interActionModel.setIndex(COMMIT_RQT);
		interActionModel.setUrl(getString(R.string.first_url)
				+ getString(R.string.first_url_page));
		interActionModel.setMessage(message);
		weakRefAsyncTask.execute(interActionModel);
	}
}
